package com.suxii.netty_demo.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.suxii.netty_demo.R;
import com.suxii.service.MyNettyService;
import com.suxii.test.Main;
import com.suxii.utils.Global;
import com.suxii.widget.NoBar;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText loginUid;
    private EditText loginPassword;

    private Context context;

    private Button login_btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        NoBar.setNoBar(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        loginUid = findViewById(R.id.login_uid);
        loginPassword = findViewById(R.id.login_password);

        login_btn=findViewById(R.id.login_btn);

        context=this;

        init();
    }

    private void init(){
        File file = new File(context.getFilesDir(), "info.sx");
        // 文件存在则读取账户信息
        if (file.isFile()) {
            String[] s = null;
            try (var fis = new FileInputStream(file);
                 var br = new BufferedReader(new InputStreamReader(fis))) {
                String line = br.readLine();
                s = line.split("#");
                //Global.uid= Integer.valueOf(s[0]);
                //Log.e("aa","uid:"+Global.uid);

            } catch (Exception e) {
                e.printStackTrace();
            }
            success(Integer.valueOf(s[0]),s[1]);
        }

    }

    private boolean isLogin=false;
    public void loginBtn(View view) {
        login_btn.setText(isLogin?"登  录":"登录中...");
        if (isLogin){

            //isLogin=false;
        }else {
            isLogin=true;
            String uid = loginUid.getText().toString();
            String password = loginPassword.getText().toString();
            if (!(uid.isEmpty() && password.isEmpty())) {

                //服务线程不安全
                //先将服务停掉
                Intent in = new Intent(this, MyNettyService.class);
                stopService(in);
                // 重新登录
                new Thread(() -> {

                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(getString(R.string.url) + "user?uid=" + uid + "&password=" + password)
                            .get()
                            .build();
                    Call call = okHttpClient.newCall(request);
                    try {
                        Response execute = call.execute();
                        String s = execute.body().string();

                        JsonObject jsonObject = new Gson().fromJson(s, JsonObject.class);
                        JsonElement data = jsonObject.get("data");
                        Log.e("aa", String.valueOf(data));
                        if (String.valueOf(data).equals("null")) {
                            Looper.prepare();
                            Toast.makeText(context, "账号或密码错误", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                            Log.e("aa", "账号或密码错误");
                        } else {
                            JsonObject json = new Gson().fromJson(data, JsonObject.class);
                            //Log.e("aa", String.valueOf(json.get("name")));
                            String name = json.get("name").toString();
                            name = name.replace("\"", "");
                            File file = new File(context.getFilesDir(), "info.sx");
                            try (FileOutputStream fos = new FileOutputStream(file)) {
                                fos.write((uid + "#" + name).getBytes(StandardCharsets.UTF_8));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            isLogin=false;
                            login_btn.post(()->
                            login_btn.setText(isLogin?"登  录":"登录中...")
                            );
                            // 登录成功，跳转主页
                            success(Integer.valueOf(uid), name);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }).start();
            }
        }
    }

    private void success(Integer uid,String name) {
        Global.setUid(uid);
        Global.name=name+"("+uid+")";
        Intent intent=new Intent(this, Suxii.class);
        startActivity(intent);
        finish();
    }
}